//
//  RHMePriceTimeRangeCell.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/22.
//

#import "RHMePriceTimeRangeCell.h"
@interface RHMePriceTimeRangeCell()
@property (nonatomic ,strong) NSMutableArray *optionBtnArr;//尖,峰,平,谷按钮

@property (nonatomic ,strong) NSMutableArray *timeBtnArr;//时间段按钮

@property (nonatomic ,strong) NSArray *btnColors;

@property (nonatomic ,strong) NSMutableArray *jianArr;

@property (nonatomic ,strong) NSMutableArray *fengArr;

@property (nonatomic ,strong) NSMutableArray *pingArr;

@property (nonatomic ,strong) NSMutableArray *guArr;

@property (nonatomic ,strong) QMUIButton *currentBtn;

@property (nonatomic ,strong) UIPanGestureRecognizer *pan;

@property (nonatomic ,strong) NSArray *keys;

@property (nonatomic ,strong) QMUIButton *startBtn;//手势滑动开始点击的按钮

@property (nonatomic ,strong) QMUIButton *endBtn;//手势滑动结束时点击的按钮,结束后这个区间的按钮都选上
@end
@implementation RHMePriceTimeRangeCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self setupUI];
    }
    return self;
}

-(void)setTimeArr:(NSMutableArray *)timeArr
{
    if (timeArr.count<self.timeBtnArr.count) {
        return;
    }
    _timeArr = timeArr;
    kWeakSelf;
    [_timeArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger time_idx, BOOL * _Nonnull stop) {
        QMUIButton *timeBtn = [self.timeBtnArr safeObjectAtIndex:time_idx];
        [weakSelf.keys enumerateObjectsUsingBlock:^(NSString*  _Nonnull key, NSUInteger type_idx, BOOL * _Nonnull stop) {
            if ([dic[@"type"] isEqualToString:key]) {
                QMUIButton *typeBtn = [weakSelf.optionBtnArr safeObjectAtIndex:type_idx];
                typeBtn.selected = YES;
                NSString *colorStr = weakSelf.btnColors[type_idx];
                [typeBtn setBackgroundColor:typeBtn.selected?kCOLOR_HEX(colorStr):kCOLOR_HEX_A(colorStr, 0.2)];
                
                timeBtn.selected = YES;
                [timeBtn setBackgroundColor:kCOLOR_HEX(weakSelf.btnColors[type_idx])];
            }
        }];
    }];
    
}

- (void)setupUI{
    kWeakSelf;
    self.keys = @[@"tip",@"peak",@"flat",@"valley"];
    self.timeArr = [NSMutableArray array];
    self.optionBtnArr = [NSMutableArray array];
    self.timeBtnArr = [NSMutableArray array];
    self.jianArr = [NSMutableArray array];
    self.fengArr = [NSMutableArray array];
    self.pingArr = [NSMutableArray array];
    self.guArr   = [NSMutableArray array];
    [self setBackgroundColor:UIColor.clearColor];
    [self.contentView setBackgroundColor:UIColor.clearColor];
    
    UIView *bgView = [[UIView alloc]init];
    [self.contentView addSubview:bgView];
    bgView.backgroundColor = [UIColor whiteColor];
    [bgView rounded:8 width:1 color:kBorderColor];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 15, 5, 15));
    }];
    
    

    QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:kCOLOR_HEX(@"#303133") textAligment:NSTextAlignmentLeft];
    titleLab.text = @"时段设置".rh_localized;
    titleLab.numberOfLines = 2;
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.top.mas_offset(10);
        
    }];
    
    QMUILabel *tipsLab = [QMUILabel labelWithFont:kSYSTEMFONT(12) textColor:kCOLOR_HEX(@"#8B8D92") textAligment:NSTextAlignmentLeft];
    tipsLab.text = @"(先选择时段标志，再点击时段设置)".rh_localized;
    tipsLab.numberOfLines = 2;
    [bgView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.top.equalTo(titleLab.mas_bottom).offset(10);
        make.right.mas_offset(-15);
    }];
    UIView *tempView = tipsLab;
    
    __block BOOL isDetail = [self.reuseIdentifier isEqualToString:@"RHMePriceTimeRangeCell_detail"];
    if (isDetail) {
        tempView = titleLab;
        tipsLab.hidden = YES;
    }

    __block UIView *lastBtn;
    NSArray *buttonTitles = @[@"尖",@"峰",@"平",@"谷"];
    self.btnColors = @[@"#357AF6",@"#7B61FF",@"#FE8C47",@"#12CBB9"];
    CGFloat btnWidth = (kUI_WINDOW_W - 30 - (15*5))/4;
    [buttonTitles enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *colorStr = weakSelf.btnColors[idx];
        QMUIButton *typeBtn = [QMUIButton buttonWithTitle:title.rh_localized titleColor:kCOLOR_HEX(colorStr) titleFont:kSYSTEMFONT(14)];
        [typeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        typeBtn.tag = idx;
        if (isDetail) {
            typeBtn.userInteractionEnabled = NO;
        }
        [bgView addSubview:typeBtn];
        [weakSelf.optionBtnArr addObject:typeBtn];
        if (lastBtn) {
            [typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastBtn.mas_right).offset(15);
                make.width.offset(btnWidth);
                make.height.offset(32);
                make.top.equalTo(lastBtn);
            }];
        }else{
            [typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(15);
                make.width.offset(btnWidth);
                make.height.offset(32);
                make.top.equalTo(tempView.mas_bottom).offset(15);
            }];
        }
       
        [typeBtn setCornerRadius:5];
        [typeBtn setBackgroundColor:kCOLOR_HEX_A(colorStr, 0.2)];
        typeBtn.layer.borderColor = kCOLOR_HEX(colorStr).CGColor;
        typeBtn.layer.borderWidth = 1;
        typeBtn.layer.masksToBounds = YES;
        lastBtn = typeBtn;
        
        [[typeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf clearOtherBtnStatus:colorStr];
            x.selected = !x.selected;
            [x setBackgroundColor:x.selected?kCOLOR_HEX(colorStr):kCOLOR_HEX_A(colorStr, 0.2)];
            weakSelf.currentBtn = x;
            weakSelf.pan.enabled = YES;
        }];
    }];
    
    UIView *btnView = kView;
    [bgView addSubview:btnView];
    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(lastBtn.mas_bottom).offset(10);
        make.bottom.mas_offset(-15);
    }];
    CGFloat timeBtnWidth = (kUI_WINDOW_W-30-30+3)/4;
    __block QMUIButton *lastTimeBtn;
   
    for (int i = 0; i<48; i++) {
        [self.timeArr addObject:@{}];
        NSInteger start = i*30;
        NSInteger end = start + 30;
      
        NSString *btnTitle = [NSString stringWithFormat:@"%02ld:%02ld-%02ld:%02ld",start/60,start%60,end/60,end%60];
        QMUIButton *timeBtn = [QMUIButton buttonWithTitle:btnTitle titleColor:kCOLOR_HEX(@"#303133") titleFont:kSYSTEMFONT(12)];
        [timeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        timeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        timeBtn.titleLabel.minimumScaleFactor = 0.8;
        if (isDetail) {
            timeBtn.userInteractionEnabled = NO;
        }
        [btnView addSubview:timeBtn];
        [self.timeBtnArr addObject:timeBtn];
        [timeBtn setBackgroundColor:kCOLOR_HEX(@"#F4F6F9")];
        timeBtn.layer.borderColor = kBorderColor.CGColor;
        timeBtn.layer.borderWidth = 1;
        timeBtn.layer.masksToBounds = YES;
        timeBtn.tag = 100+i;
        if (lastTimeBtn) {
            if (i%4==0) {
                [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_offset(0);
                    make.size.equalTo(lastTimeBtn);
                    make.top.equalTo(lastTimeBtn.mas_bottom).offset(-1);
                }];
            }else{
                [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lastTimeBtn.mas_right).offset(-1);
                    make.size.equalTo(lastTimeBtn);
                    make.top.equalTo(lastTimeBtn);
                }];
            }
        }else{
            [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(0);
                make.width.offset(timeBtnWidth);
                make.height.offset(44);
                make.top.mas_offset(0);
            }];
        }
        lastTimeBtn = timeBtn;
        
        [[timeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof QMUIButton * _Nullable x) {
            if (weakSelf.currentBtn) {
                x.selected = YES;
                NSInteger index = weakSelf.currentBtn.tag;
                [x setBackgroundColor:kCOLOR_HEX(weakSelf.btnColors[index])];
                
                if (index == 0 &&  ![weakSelf.jianArr containsObject:x]) {
                    [weakSelf.jianArr addObject:x];
                }
                if (index == 1 &&  ![weakSelf.fengArr containsObject:x]) {
                    [weakSelf.fengArr addObject:x];
                }
                if (index == 2 &&  ![weakSelf.pingArr containsObject:x]) {
                    [weakSelf.pingArr addObject:x];
                }
                if (index == 3 &&  ![weakSelf.guArr containsObject:x]) {
                    [weakSelf.guArr addObject:x];
                }
                [weakSelf updateButtonParamterWithIndex:x.tag-100];
            }
            
        }];
    }
    [lastTimeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
    }];
    
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [btnView addGestureRecognizer:pan];
    pan.enabled = NO;
    self.pan = pan;
    
}

-(void)setCanPan:(BOOL)canPan
{
    _canPan = canPan;
    self.pan.enabled = canPan;
}
-(void)panAction:(UIPanGestureRecognizer*)recognize
{
    CGPoint point = [recognize locationInView:recognize.view];
//    NSLog(@"---->%@",NSStringFromCGPoint(point));
//    if (recognize.state == UIGestureRecognizerStateBegan) {
//        NSString *view_class = [recognize.view class];
//        NSLog(@"开始点击的view----->%@",view_class);
//    }
//    if (recognize.state == UIGestureRecognizerStateEnded) {
//        NSString *view_class = [recognize.view class];
//        NSLog(@"结束点击的view----->%@",view_class);
//    }
    kWeakSelf;
    [self.timeBtnArr enumerateObjectsUsingBlock:^(QMUIButton*  _Nonnull timeBtn, NSUInteger idx, BOOL * _Nonnull stop) {
        if ( CGRectContainsPoint(timeBtn.frame, point)) {
            if (weakSelf.currentBtn) {
                NSInteger index = self.currentBtn.tag;
                timeBtn.selected = YES;
                [weakSelf changeButtonStatus:timeBtn];
                //尖
                if (index == 0) {
                    if (![weakSelf.jianArr containsObject:timeBtn]) {
                        [weakSelf.jianArr addObject:timeBtn];
                    }
                    
                    //滑过的其他按钮也选中
                    if (recognize.state == UIGestureRecognizerStateBegan) {
                        weakSelf.startBtn = timeBtn;
                        NSLog(@"---->开始点击的按钮%ld",timeBtn.tag);
                    }else{
                        NSLog(@"---->正在点击的按钮%ld",timeBtn.tag);
                        [weakSelf selectOtherButtonWithStartIndex:weakSelf.startBtn.tag-100 endIndex:idx typeSelectArray:weakSelf.jianArr];
                        
                    }
                    
                }
                
                //峰
                if (index == 1) {
                    if (![weakSelf.fengArr containsObject:timeBtn]) {
                        [weakSelf.fengArr addObject:timeBtn];
                    }
                    
                    //滑过的其他按钮也选中
                    if (recognize.state == UIGestureRecognizerStateBegan) {
                        weakSelf.startBtn = timeBtn;
                        NSLog(@"---->开始点击的按钮%ld",timeBtn.tag);
                    }else{
                        NSLog(@"---->正在点击的按钮%ld",timeBtn.tag);
                        [weakSelf selectOtherButtonWithStartIndex:weakSelf.startBtn.tag-100 endIndex:idx typeSelectArray:weakSelf.fengArr];
                        
                    }
                }
                
                //平
                if (index == 2) {
                    if (![weakSelf.pingArr containsObject:timeBtn]) {
                        [weakSelf.pingArr addObject:timeBtn];
                    }
                   
                    //滑过的其他按钮也选中
                    if (recognize.state == UIGestureRecognizerStateBegan) {
                        weakSelf.startBtn = timeBtn;
                        NSLog(@"---->开始点击的按钮%ld",timeBtn.tag);
                    }else{
                        NSLog(@"---->正在点击的按钮%ld",timeBtn.tag);
                        [weakSelf selectOtherButtonWithStartIndex:weakSelf.startBtn.tag-100 endIndex:idx typeSelectArray:weakSelf.pingArr];
                        
                    }
                }
                
                //谷
                if (index == 3) {
                    if (![weakSelf.guArr containsObject:timeBtn]) {
                        [weakSelf.guArr addObject:timeBtn];
                    }
                    
                    //滑过的其他按钮也选中
                    if (recognize.state == UIGestureRecognizerStateBegan) {
                        weakSelf.startBtn = timeBtn;
                        NSLog(@"---->开始点击的按钮%ld",timeBtn.tag);
                    }else{
                        NSLog(@"---->正在点击的按钮%ld",timeBtn.tag);
                        [weakSelf selectOtherButtonWithStartIndex:weakSelf.startBtn.tag-100 endIndex:idx typeSelectArray:weakSelf.guArr];
                        
                    }
                }
                [weakSelf updateButtonParamterWithIndex:timeBtn.tag-100];
            }
        }
       
    }];
   
}

//滑动到的按钮区间选择
-(void)selectOtherButtonWithStartIndex:(NSInteger)startIndex  endIndex:(NSInteger)endIndex typeSelectArray:(NSMutableArray*)selectArr
{
    
    for (NSInteger i = MIN(startIndex, endIndex); i<= MAX(startIndex, endIndex); i++) {
        QMUIButton *selectBtn = [self.timeBtnArr safeObjectAtIndex:i];
        selectBtn.selected = YES;
        [self changeButtonStatus:selectBtn];
        if (selectBtn&&![selectArr containsObject:selectBtn]) {
            [selectArr addObject:selectBtn];
            [self updateButtonParamterWithIndex:i];
        }
        [self updateButtonParamterWithIndex:selectBtn.tag - 100];
    }
}

//更新所选按钮的参数回传给控制器
-(void)updateButtonParamterWithIndex:(NSInteger)index
{
    NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
    NSString *key = self.keys[self.currentBtn.tag];
    [mtbDic setObject:key forKey:@"type"];
    [mtbDic setObject:@(index) forKey:@"index"];
    
    [self.timeArr replaceObjectAtIndex:index withObject:mtbDic];
    NSLog(@"---->%@",self.timeArr.yy_modelDescription);
    if (self.updateTimeArr) {
        self.updateTimeArr(self.timeArr);
    }
}

//根据选择状态设置按钮
-(void)changeButtonStatus:(QMUIButton*)btn
{
    if (btn.isSelected) {
        [btn setBackgroundColor:kCOLOR_HEX(self.btnColors[self.currentBtn.tag])];
       
    }else{
        [btn setBackgroundColor:kCOLOR_HEX(@"#F4F6F9")];
    }
}

//清除选项按钮状态
-(void)clearOtherBtnStatus:(NSString*)normalColor
{
    kWeakSelf;
    [self.optionBtnArr enumerateObjectsUsingBlock:^(QMUIButton*  _Nonnull btn, NSUInteger idx, BOOL * _Nonnull stop) {
        btn.selected = NO;
        btn.backgroundColor = kCOLOR_HEX_A(weakSelf.btnColors[idx], 0.2);
    }];
}

@end
